<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/20
 * Time: 16:50
 */
namespace App\Http\Controllers\web;

use App\Models\V1\AudioModel;
use App\Models\V1\CommentModel;
use App\Models\V1\MemberModel;
use App\Repository\WxUserInfoRegister;
use App\Repository\Comment;
use Illuminate\Session;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntMindShare;
use App\Module\EntBookHots;
use App\Models\V1\BookModel;
use App\Http\Controllers\Weixin\WeixinServiceController;
use DB;
use Illuminate\Support\Facades\Cookie;
use Excel;



class HomeController extends Controller
{
    use WxUserInfoRegister;
    use Comment;

    //======================== 分享页面 begin ============================

    /*热门文章详情页面*/
    public function infodetail($id)
    {
        $entMindShare = EntMindShare::findOrFail($id);
        DB::table('mindshare')->where('MinSgaID',$id)->increment('view_times');
        return view('web/home/info', ['sharedetail' => $entMindShare]);
    }

    /*热门推荐书籍*/
    public function advertisingdetail($id)
    {
        $entBookHots = EntBookHots::findOrFail($id);
        return view('web/home/hotdetail', ['hotsdetail' => $entBookHots]);
    }


    /**
     * 自课堂公司文档资料
     * */
    public function company_source_detail(Request $request)
    {
        $sourceId   = $request->input('sourceId');
        $sourceInfo = DB::table('company_source')->where('id',$sourceId)->first();
        return view('web/home/source-detail',['sourceInfo'=>$sourceInfo]);
    }


    /*心灵分享到微信端*/
    public function mind_share_to_weixin(Request $request)
    {
        $articleId = $request->input('articleId', 0);
        $parent = $request->input('parentId', 0);
        DB::table('mindshare')->where('MinSgaID',$articleId)->increment('view_times');
        //获得文章内容
        $articleInfo = EntMindShare::findOrFail($articleId);
        $weixinController = new WeixinServiceController();
        $weixinApp = $weixinController->get_weixin_app();
        $weixinJs = $weixinApp->js;
        $data = [
            'shareDetail' => $articleInfo,
            'parent' => $parent,
            "weixinJs" => $weixinJs,
            'articleId' => $articleId
        ];
        return view('web/home/share-mind-share', $data);
    }


    /*热门书籍分享到微信*/
    public function hot_book_share_to_weixin(Request $request)
    {
        $bookId = $request->input('bookId');
        $parentId = $request->input('parentId');

        $entBookHots = EntBookHots::findOrFail($bookId);
        return view('web/home/hot-book-share', ['bookInfo' => $entBookHots, 'parent' => $parentId]);
    }


    /**
     * 音频分享
     * */
    public function audio_share_to_weixin(Request $request)
    {
        $audioId = $request->input('audioId');
        $parentId = $request->input('parentId');
        $audioModel = new AudioModel();
        $audioModel->add_audio_view_times($audioId);
        $audioInfo = $audioModel->get_audio_info($audioId);

        $weixinController = new WeixinServiceController();
        $weixinApp = $weixinController->get_weixin_app();
        $weixinJs = $weixinApp->js;
        $data = [
            'parent' => $parentId,
            "weixinJs" => $weixinJs,
            'audioInfo' => $audioInfo
        ];
        //修改播放次数
        return view('web/home/audio-share', $data);
    }


    /**
     * 读书改进计划分享
     * */
    public function share_read_plan(Request $request)
    {
        $userId = $request->input('userId',0);
        $bookId = $request->input('bookId',0);

        $bookModel = new BookModel();
        $memberModel = new MemberModel();

        $bookInfo = $bookModel->get_book_info($bookId);

        if($userId > 0)
        {
            $memberInfo = $memberModel->get_member_info_by_id($userId);

            $readPlanInfo = DB::table('booksumup')
                ->where('BookID', $bookId)
                ->where('MemNumber', $memberInfo->MemNumber)
                ->orderBy('SumUpID', 'desc')
                ->first();

        } else {

            $readPlanInfo = false;
            $memberInfo   = false;

        }

        //获取书籍评论
        $comments = $this->get_multy_grade_comments($bookId,5);

        $weixinController = new WeixinServiceController();
        $weixinApp = $weixinController->get_weixin_app();
        $weixinJs = $weixinApp->js;

        return view('web/home/share-read-plan', [
            'bookInfo'      => $bookInfo,
            'readPlanInfo'  => $readPlanInfo,
            'memberInfo'    => $memberInfo,
            "weixinJs"      => $weixinJs,
            "comments"      => $comments
        ]);
    }


    public function share_guozheng_video(Request $request)
    {
        $bookId     = $request->input('bookId');
        $userId     = 0;
        $bookModel  = new BookModel();
        $videoInfo  = $bookModel->get_book_info($bookId);
        $videoInfo->desc   = str_replace(array("\r\n", "\r", "\n"," ","\""),"",$videoInfo->BookDesc);
        DB::table('bookinfo')->where('BookID',$bookId)->increment('ReadNumber');
        $type       = 3;
        $comments   = $this->get_multy_grade_comments($bookId,$type,0,$userId);

        $allVideos  = $bookModel->get_gz_videos();
        $recommends = [];
        foreach($allVideos as $video)
        {
            array_push($recommends,$video);
            if(count($recommends) == 2)
            {
                break;
            }
        }


        $weixinController = new WeixinServiceController();
        $weixinApp = $weixinController->get_weixin_app();
        $weixinJs = $weixinApp->js;


        $data   = [
            'videoInfo'         => $videoInfo,
            'comments'          => $comments,
            'recommendVideos'   => $recommends,
            "weixinJs"          => $weixinJs
        ];
        return view('web/home/share-guozheng-video',$data);

        return $this->apiData
            ->set_data('videoInfo',$videoInfo)
            ->set_data('comments',$comments)
            ->set_data('recommendVideos',$recommends)
            ->send(200,'ok');

    }
    //======================== 分享页面 end ============================
    /*
     * 关于我们
     * */
    public function aboutUs()
    {
        return view('web/home/aboutus');
    }


    //======================= APP内嵌页面  begin =======================
    public function app_page_live_desc()
    {
        return view('web/home/app-page-live-desc');
    }

    /**
     * app直播订阅界面
     * */
    public function app_page_live_dingyue(Request $request)
    {
        $liveId = $request->input('liveId',0);
        $mobile = $request->input('mobile','');
        $key    = $request->input('key','');

        $liveInfo   = DB::table('live')->where('id',$liveId)->first();

        if(!$liveInfo)
        {
            return apiData()->notice('直播不存在');
        }

        $db     = new MemberModel();
        $member = $db->get_member_info_by_mobile_key($mobile,$key);
        if(!($mobile && $key))
        {
            return apiData()->notice('缺少参数');
        }
        if(!$member)
        {
            return apiData()->notice('用户不存在');
        }

        $data           = $member;
        $data->liveId   = $liveId;

        return view('web/home/app-page-live-dingyue',['data'=>$data]);
    }

    //======================= APP内嵌页面  end   =======================


    /*学习官提示信息*/
    public function book_inner(Request $request)
    {
        $bookId = $request->input('bookId');
        $imgs = DB::table('bookimg')->where('BookID',$bookId)->pluck('FilePath1');

        return view('web/home/book-inner',[ 'imgs' => $imgs ]);
    }

    public function ios_upgrade()
    {
        return view('web/home/ios-upgrade');
    }


    public function clean_session(Request $request){
        $sessions = $request->session()->all();
        print_r($sessions);
        $request->session()->flush();
        return 'ok';
    }


    public function clean_cookie(Request $request)
    {
        Cookie::forget('wxUnionId');
        return "ok";
    }

    /**
     * 学习官系统后台登录
     * */
    public function clo_system_wx_login(Request $request)
    {

        //return "<h2 style='text-align: center;padding:20px 0;'>系统升级中...</h2><p style='text-align: center;'>如需提交订单，请联系客服.</p>";

        $userInfo = $this->get_wx_user_info();
        $openId = $userInfo['WeiXID'];

        $weixinService  = new WeixinServiceController();
        $weixinApp      = $weixinService->get_weixin_app(2);
        $accessToken    = $weixinApp->access_token;
        $token          = $accessToken->getToken();

        $isSubscript    = $weixinService->isSubscribe($openId,$token);

        if($isSubscript == false){
            return view('other/weixin-subscribe');
        }

        $url = env('ADMIN_HOST') . "/cloAdmin/dist#/autologin";
        Cookie::queue("wxUnionId",$userInfo['wx_unionid'],10000);
        return view('other/location-replace',['url'=>$url]);
    }


    /**
     * 教导读书会一周年
     * */
    public function jiaodao_one_year()
    {
        $weixinController = new WeixinServiceController();
        $weixinApp  = $weixinController->get_weixin_app();
        $weixinJs   = $weixinApp->js;
        $data       = ["weixinJs" => $weixinJs];
        return view('web/home/jiaodao-one-year',$data);
    }


    public function article_detail(Request $request)
    {
        $articleId      = $request->input('articleId');
        $articleInfo    = DB::table('articles')->where('articleId',$articleId)->first();
        return view('web/home/article-detail',['articleInfo'=>$articleInfo]);
    }

    public function vcool(Request $i) {
        $act = $i->input('act','share');
        if($act == 'share') {
            echo "<script>location.replace('https://5.u.mgd5.com/c/clte/af5u/index.html')</script>";
            exit;
        }
        $weixinController = new WeixinServiceController();
        $weixinApp = $weixinController->get_weixin_app();
        $weixinJs = $weixinApp->js;
        $data       = ["weixinJs" => $weixinJs];
        return view('web/home/vcool',$data);
    }

    public function coolDataSave(Request $i) {
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        $total = $this->coolOrderNum(1);
        if($total >= 999) {
            return response()->json(['id'=>0,'msg'=>'抱歉，礼物已被领取完了']);
        }

        $id = $i->input('id',0);
        $data = $i->only('num','mobile','name','address','carCode','carType','beginDay','endDay','province','city','county','shop');
        if($data['shop']['parentId'] == '999999') {
            $data['shop'] = '';
        } else {
            $data['shop'] = json_encode($data['shop']);
        }

        $data['createdAt'] = date('Y-m-d H:i:s');
        if($id > 0) {
            $id = DB::table('vcool')->where('id',$id)->update($data);
        } else  {
            //检查内容是否提交过
            if(self::coolCheck('mobile', $data['mobile'])) {
                return response()->json(['id'=>0,'msg'=>'本手机号已经领取过']);
            }
            if(self::coolCheck('carCode',$data['carCode'])) {
                return response()->json(['id'=>0,'msg'=>'本车牌已经领取过']);
            }

            $id = DB::table('vcool')->insertGetId($data);
        }
        return response()->json(['id'=>$id,'msg'=>'领取成功']);
    }

    //检查总数量，超过999停止
    public function coolOrderNum($type = 0) {
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        //选择门店的算两单
        $total = DB::table('vcool')->sum('num');
        if(time() > strtotime('2020-07-05 23:59:59')) {
            $total = 1000;
        }
        if($type === 1) {
            return $total;
        }
        return response($total);
    }

    public static function coolCheck($key,$value) {
        return DB::table('vcool')->where($key,$value)->first();
    }
    public function coolDataShow(Request $i) {
        $orders = DB::table('vcool')->orderBy('id','desc')->get();
        $export = $i->input('export',0);
        $delimiter = $export ? '-' : '<br/>';
        foreach($orders as $order) {
            $order->address = $order->province.$order->city.$order->county.$order->address;
            if($order->shop) {

                $shop = json_decode($order->shop);
                $detail = '店名:'.$shop->name.$delimiter.'编号:'.$shop->code.$delimiter.'电话:'.$shop->phone.$delimiter.'地址:'.$shop->address;
                $order->shop = $detail;
                $order->hasShop = true;
            } else {
                $order->hasShop = false;
            }
        }
        if($export) {
            $excelData = [['姓名','手机','地址','车标','车牌','数量','是否门店预约','门店内容','申领时间']];
            $types = ['bp'=>'博派','kp'=>'狂派'];
            foreach($orders as $o) {
                $excelData[] = [$o->name,$o->mobile,$o->address,$types[$o->carType],$o->carCode,$o->num,$o->hasShop?'是':'否',$o->shop,$o->createdAt];
            }
            ob_end_clean();//解决乱码核心 就在此处添加此函数
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="test_list.xls"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
            header('Cache-Control: cache, must-revalidate');
            header('Pragma: public');

            Excel::create('orders',function($excel) use ($excelData){  //创建一个文件
                $excel->sheet('index', function($sheet) use ($excelData){ //创建一张表
                    $sheet->rows($excelData);
                });
            })->export('xls');
        } else {
            return view('web/home/vcool-data',['orders' => $orders]);
        }
    }
}
